<template>
    <!-- 文件预览弹窗 -->
    <el-dialog
        v-model="previewVisible"
        :title="'文件预览'"
        width="80%"
        :close-on-click-modal="true"
        :close-on-press-escape="true"
        class="file-preview-dialog"
    >
        <div class="file-preview-content">
            <div v-if="previewType === 'image'" class="image-preview">
                <img :src="previewUrl" :alt="previewFileName" class="preview-image" />
            </div>
            <div v-else-if="previewType === 'video'" class="video-preview">
                <video :src="previewUrl" controls class="preview-video">
                    您的浏览器不支持视频播放
                </video>
            </div>
            <div v-else-if="previewType === 'audio'" class="audio-preview">
                <audio :src="previewUrl" controls class="preview-audio">
                    您的浏览器不支持音频播放
                </audio>
            </div>
            <div v-else-if="previewType === 'pdf'" class="pdf-preview">
                <iframe :src="previewUrl" class="preview-iframe" frameborder="0"></iframe>
            </div>
            <div v-else-if="previewType === 'text'" class="text-preview">
                <pre class="preview-text">{{ previewContent }}</pre>
            </div>
            <div v-else-if="previewType === 'office'" class="office-preview">
                <div class="office-preview-content">
                    <el-icon class="file-icon-large"><Document /></el-icon>
                    <p class="file-name">{{ previewFileName }}</p>
                    <p class="file-tip">Office文档需要下载后使用相应软件打开</p>
                    <el-button type="primary" @click="downloadInNewTab">在新标签页中打开</el-button>
                </div>
            </div>
            <div v-else class="unsupported-preview">
                <el-icon class="file-icon-large"><Document /></el-icon>
                <p class="file-name">{{ previewFileName }}</p>
                <p class="file-tip">此文件类型不支持预览，请下载后查看</p>
                <el-button type="primary" @click="downloadInNewTab">在新标签页中打开</el-button>
            </div>
        </div>
    </el-dialog>

    <el-dialog v-model="visible" title="审核申请" width="800px" @close="handleClose">
        <div v-if="reviewData" class="review-content">
            <!-- 基本信息 -->
            <el-card class="mb-4">
                <template #header>
                    <span class="font-bold">基本信息</span>
                </template>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <div class="info-item">
                            <label>申请人：</label>
                            <span>{{ reviewData.user?.nickname || reviewData.user_id }}</span>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="info-item">
                            <label>代理类型：</label>
                            <el-tag :type="getAgentTypeTagType(reviewData.agent_type)">
                                {{ getAgentTypeText(reviewData.agent_type) }}
                            </el-tag>
                        </div>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 区域信息 -->
            <el-card class="mb-4" v-if="getProvinceText() || getCityText() || getAreaText()">
                <template #header>
                    <span class="font-bold">区域信息</span>
                </template>
                <el-row :gutter="20">
                    <el-col :span="8" v-if="getProvinceText()">
                        <div class="info-item">
                            <label>省份：</label>
                            <span>{{ getProvinceText() }}</span>
                        </div>
                    </el-col>
                    <el-col :span="8" v-if="getCityText()">
                        <div class="info-item">
                            <label>城市：</label>
                            <span>{{ getCityText() }}</span>
                        </div>
                    </el-col>
                    <el-col :span="8" v-if="getAreaText()">
                        <div class="info-item">
                            <label>区域：</label>
                            <span>{{ getAreaText() }}</span>
                        </div>
                    </el-col>
                </el-row>
            </el-card>

            <!-- 申请理由 -->
            <el-card class="mb-4">
                <template #header>
                    <span class="font-bold">申请理由</span>
                </template>
                <div class="apply-reason">
                    {{ reviewData.apply_reason || '无' }}
                </div>
            </el-card>

            <!-- 附件信息 -->
            <el-card v-if="reviewData.files && reviewData.files.length" class="mb-4">
                <template #header>
                    <span class="font-bold">附件信息</span>
                </template>
                <div class="files-display">
                    <div v-for="(file, index) in reviewData.files" :key="index" class="file-item">
                        <div class="file-info">
                            <el-icon class="file-icon">
                                <Document />
                            </el-icon>
                            <div class="file-details">
                                <div class="file-name">{{ getFileName(file) }}</div>
                                <div class="file-url">{{ fullUrl(file) }}</div>
                            </div>
                            <div class="file-actions">
                                <el-button 
                                    type="primary" 
                                    size="small" 
                                    @click="openFile(file)"
                                >
                                    打开
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 拒绝理由输入 -->
            <el-card v-if="showRejectReason" class="mb-4">
                <template #header>
                    <span class="font-bold">拒绝理由</span>
                </template>
                <el-input
                    v-model="rejectForm.reject_reason"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入拒绝理由"
                    maxlength="255"
                    show-word-limit
                />
            </el-card>
        </div>
        
        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="danger" @click="handleReject" v-if="!showRejectReason">拒绝</el-button>
            <el-button type="danger" @click="confirmReject" v-if="showRejectReason">确认拒绝</el-button>
            <el-button type="primary" @click="handleApprove" v-if="!showRejectReason">通过审核</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import { fullUrl } from '/@/utils/common'
import createAxios from '/@/utils/axios'

interface Props {
    modelValue: boolean
    data: any
}

interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
})

const reviewData = ref<any>(null)
const showRejectReason = ref(false)
const rejectForm = ref({
    id: 0,
    reject_reason: ''
})
const fileList = ref<any[]>([])

// 文件预览相关
const previewVisible = ref(false)
const previewUrl = ref('')
const previewFileName = ref('')
const previewType = ref('')
const previewContent = ref('')

// 区域信息显示逻辑
const getProvinceText = () => {
    if (!reviewData.value?.province) return ''
    const province = reviewData.value.province
    if (Array.isArray(province)) {
        return province.length > 0 ? province[0] : ''
    }
    return province
}

const getCityText = () => {
    if (!reviewData.value?.city) return ''
    const city = reviewData.value.city
    if (Array.isArray(city)) {
        return city.length > 0 ? city[0] : ''
    }
    return city
}

const getAreaText = () => {
    if (!reviewData.value?.area) return ''
    const area = reviewData.value.area
    if (Array.isArray(area)) {
        return area.length > 0 ? area[0] : ''
    }
    return area
}

// 获取代理类型文本
const getAgentTypeText = (type: string) => {
    const typeMap: Record<string, string> = {
        'province_agent': '省级代理',
        'city_agent': '市级代理',
        'area_agent': '区级代理'
    }
    return typeMap[type] || type
}

// 获取代理类型标签类型
const getAgentTypeTagType = (type: string) => {
    const typeMap: Record<string, string> = {
        'province_agent': 'danger',
        'city_agent': 'warning',
        'area_agent': 'success'
    }
    return typeMap[type] || 'info'
}

// 初始化文件列表
const initFileList = (files: string[]) => {
    fileList.value = files.map((file, index) => ({
        name: getFileName(file),
        url: file,
        uid: index + 1,
        status: 'success'
    }))
}

// 获取文件名
const getFileName = (fileUrl: string) => {
    if (!fileUrl) return '未知文件'
    const urlParts = fileUrl.split('/')
    return urlParts[urlParts.length - 1] || '未知文件'
}

// 打开文件预览
const openFile = (fileUrl: string) => {
    if (!fileUrl) {
        ElMessage.warning('文件链接无效')
        return
    }
    
    const fullFileUrl = fullUrl(fileUrl)
    const fileName = getFileName(fileUrl)
    const fileExtension = fileName.split('.').pop()?.toLowerCase() || ''
    
    console.log('原始文件URL:', fileUrl)
    console.log('完整文件URL:', fullFileUrl)
    console.log('文件扩展名:', fileExtension)
    
    // 设置预览数据
    previewUrl.value = fullFileUrl
    previewFileName.value = fileName
    previewType.value = getFileType(fileExtension)
    previewContent.value = ''
    
    // 如果是文本文件，尝试获取内容
    if (previewType.value === 'text') {
        loadTextContent(fullFileUrl)
    }
    
    // 显示预览弹窗
    previewVisible.value = true
}

// 获取文件类型
const getFileType = (extension: string) => {
    const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']
    const videoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv', 'm4v']
    const audioExts = ['mp3', 'wav', 'ogg', 'aac', 'flac', 'm4a']
    const pdfExts = ['pdf']
    const textExts = ['txt', 'md', 'json', 'xml', 'csv', 'log']
    const officeExts = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']
    
    if (imageExts.includes(extension)) return 'image'
    if (videoExts.includes(extension)) return 'video'
    if (audioExts.includes(extension)) return 'audio'
    if (pdfExts.includes(extension)) return 'pdf'
    if (textExts.includes(extension)) return 'text'
    if (officeExts.includes(extension)) return 'office'
    return 'unsupported'
}

// 加载文本内容
const loadTextContent = async (url: string) => {
    try {
        const response = await fetch(url)
        if (response.ok) {
            previewContent.value = await response.text()
        }
    } catch (error) {
        console.error('加载文本内容失败:', error)
        previewContent.value = '无法加载文件内容'
    }
}

// 在新标签页中打开文件
const downloadInNewTab = () => {
    window.open(previewUrl.value, '_blank')
    previewVisible.value = false
}


// 监听数据变化
watch(() => props.data, (newData) => {
    if (newData) {
        reviewData.value = newData
        showRejectReason.value = false
        rejectForm.value = {
            id: newData.id,
            reject_reason: ''
        }
        // 初始化文件列表
        if (newData.files && Array.isArray(newData.files)) {
            initFileList(newData.files)
        } else {
            fileList.value = []
        }
    }
}, { immediate: true })

// 关闭弹窗
const handleClose = () => {
    visible.value = false
}

// 审核通过
const handleApprove = async () => {
    try {
        await ElMessageBox.confirm(
            `确定要审核通过用户 ${reviewData.value.user?.nickname || reviewData.value.user_id} 的申请吗？`,
            '审核通过',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        
        const res = await createAxios({
            url: `/admin/region.Apply/approve?id=${reviewData.value.id}`,
            method: 'POST'
        }, {
            loading: true
        }, {
            text: '审核中...'
        })
        
        console.log('审核通过响应:', res)
        
        if (res.code === 1) {
            ElMessage.success('审核通过成功')
            handleClose()
            emit('success')
        } else {
            ElMessage.error(res.msg || '审核失败')
        }
    } catch (error) {
        // 用户取消操作
    }
}

// 显示拒绝理由输入
const handleReject = () => {
    showRejectReason.value = true
}

// 确认拒绝
const confirmReject = async () => {
    if (!rejectForm.value.reject_reason.trim()) {
        ElMessage.warning('请输入拒绝理由')
        return
    }
    
    try {
        const res = await createAxios({
            url: `/admin/region.Apply/reject?id=${rejectForm.value.id}&reject_reason=${encodeURIComponent(rejectForm.value.reject_reason)}`,
            method: 'POST'
        }, {
            loading: true
        }, {
            text: '审核中...'
        })
        
        if (res.code === 1) {
            ElMessage.success('审核拒绝成功')
            handleClose()
            emit('success')
        } else {
            ElMessage.error(res.msg || '操作失败')
        }
    } catch (error) {
        ElMessage.error('操作失败')
    }
}
</script>

<style scoped lang="scss">
.review-content {
    .mb-4 {
        margin-bottom: 16px;
    }
    
    .font-bold {
        font-weight: bold;
    }
    
    .info-item {
        margin-bottom: 12px;
        
        label {
            font-weight: 500;
            color: #606266;
            margin-right: 8px;
        }
        
        span {
            color: #303133;
        }
    }
    
    .apply-reason {
        padding: 12px;
        background-color: #f5f7fa;
        border-radius: 4px;
        line-height: 1.6;
        color: #606266;
    }
    
    .files-display {
        .file-item {
            margin-bottom: 12px;
            border: 1px solid #e4e7ed;
            border-radius: 8px;
            padding: 12px;
            background-color: #fafafa;
            
            &:last-child {
                margin-bottom: 0;
            }
            
            .file-info {
                display: flex;
                align-items: center;
                gap: 12px;
                
                .file-icon {
                    font-size: 24px;
                    color: #409eff;
                    flex-shrink: 0;
                }
                
                .file-details {
                    flex: 1;
                    min-width: 0;
                    
                    .file-name {
                        font-weight: 500;
                        color: #303133;
                        margin-bottom: 4px;
                        word-break: break-all;
                    }
                    
                    .file-url {
                        font-size: 12px;
                        color: #909399;
                        word-break: break-all;
                    }
                }
                
                .file-actions {
                    display: flex;
                    gap: 8px;
                    flex-shrink: 0;
                }
            }
        }
    }
}

// 文件预览弹窗样式
.file-preview-dialog {
    .file-preview-content {
        max-height: 70vh;
        overflow: auto;
        
        .image-preview {
            text-align: center;
            
            .preview-image {
                max-width: 100%;
                max-height: 60vh;
                object-fit: contain;
                border-radius: 4px;
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            }
        }
        
        .video-preview {
            text-align: center;
            
            .preview-video {
                max-width: 100%;
                max-height: 60vh;
                border-radius: 4px;
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            }
        }
        
        .audio-preview {
            text-align: center;
            padding: 40px 20px;
            
            .preview-audio {
                width: 100%;
                max-width: 500px;
            }
        }
        
        .pdf-preview {
            height: 60vh;
            
            .preview-iframe {
                width: 100%;
                height: 100%;
                border: none;
                border-radius: 4px;
            }
        }
        
        .office-preview {
            text-align: center;
            padding: 40px 20px;
            
            .office-preview-content {
                .file-icon-large {
                    font-size: 64px;
                    color: #409eff;
                    margin-bottom: 16px;
                }
                
                .file-name {
                    font-size: 16px;
                    font-weight: 500;
                    color: #303133;
                    margin: 16px 0 8px 0;
                }
                
                .file-tip {
                    color: #909399;
                    margin-bottom: 20px;
                }
            }
        }
        
        .text-preview {
            .preview-text {
                background-color: #f5f7fa;
                padding: 16px;
                border-radius: 4px;
                font-family: 'Courier New', monospace;
                font-size: 14px;
                line-height: 1.6;
                white-space: pre-wrap;
                word-break: break-word;
                max-height: 60vh;
                overflow: auto;
                margin: 0;
            }
        }
        
        .unsupported-preview {
            text-align: center;
            padding: 40px 20px;
            
            .file-icon-large {
                font-size: 64px;
                color: #909399;
                margin-bottom: 16px;
            }
            
            .file-name {
                font-size: 16px;
                font-weight: 500;
                color: #303133;
                margin: 16px 0 8px 0;
            }
            
            .file-tip {
                color: #909399;
                margin-bottom: 20px;
            }
        }
    }
}
</style>
